<?php
global $_GPC, $_W;
$GLOBALS['frames'] = $this->getMainMenu();
$op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
load()->func('tpl');
$shset=pdo_get('zh_gjw_shset',array('uniacid'=>$_W['uniacid']));
$pageindex = max(1, intval($_GPC['page']));
$pagesize=10;
if (!empty($_GPC['sh'])) {
    $where=' WHERE  uniacid=:uniacid and sh=:sh ';
    $data[':uniacid']=$_W['uniacid'];
    $data[':sh']=$_GPC['sh'];
    if(isset($_GPC['keywords'])){
        $where.="  and (cusname LIKE  concat('%', :name,'%') or username LIKE  concat('%', :name,'%') or phone LIKE  concat('%', :name,'%'))";
        $data[':name']=$_GPC['keywords']; 
    }
    $active=$_GPC['sh'];
    $sql="SELECT * FROM ".tablename('zh_gjw_cusmanage') .$where." ORDER BY time desc";
    $total=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('zh_gjw_cusmanage').$where." ORDER BY time desc",$data);
}else{
    $where=' WHERE  uniacid=:uniacid  ';
    $data[':uniacid']=$_W['uniacid'];
    if(isset($_GPC['keywords'])){
        $where.="  and (cusname LIKE  concat('%', :name,'%') or username LIKE  concat('%', :name,'%') or phone LIKE  concat('%', :name,'%'))";
        $data[':name']=$_GPC['keywords']; 
    }
    $active=$_GPC['sh'];
    $sql="SELECT * FROM ".tablename('zh_gjw_cusmanage') .$where." ORDER BY time desc";
    $total=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('zh_gjw_cusmanage').$where." ORDER BY time desc",$data);
}
/*
if (!empty($_GPC['sh'])) {
    $where=' WHERE  a.uniacid=:uniacid and a.sh=:sh ';
    $data[':uniacid']=$_W['uniacid'];
    $data[':sh']=$_GPC['sh'];
    if(isset($_GPC['keywords'])){
        $where.="  and (a.cusname LIKE  concat('%', :name,'%') or a.username LIKE  concat('%', :name,'%') or a.phone LIKE  concat('%', :name,'%'))";
        $data[':name']=$_GPC['keywords']; 
    }
    $active=$_GPC['sh'];
    $sql="SELECT a.*,sum(b.ofees) as ofees FROM ".tablename('zh_gjw_cusmanage'). " a left join " . tablename("zh_gjw_orders") . " b on a.id=b.cus_id " .$where." group by a.cusname ORDER BY a.time desc";
    $total=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('zh_gjw_cusmanage'). " a left join " . tablename("zh_gjw_orders") . " b on a.id=b.cus_id " .$where." group by a.cusname ORDER BY a.time desc",$data);
}else{
    $where=' WHERE  a.uniacid=:uniacid  ';
    $data[':uniacid']=$_W['uniacid'];
    if(isset($_GPC['keywords'])){
        $where.="  and (a.cusname LIKE  concat('%', :name,'%') or a.username LIKE  concat('%', :name,'%') or a.phone LIKE  concat('%', :name,'%'))";
        $data[':name']=$_GPC['keywords']; 
    }
    $active=$_GPC['sh'];
    $sql="SELECT a.*,sum(b.ofees) as ofees FROM ".tablename('zh_gjw_cusmanage'). " a left join " . tablename("zh_gjw_orders") . " b on a.id=b.cus_id " .$where." group by a.cusname ORDER BY a.time desc";
    $total=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('zh_gjw_cusmanage'). " a left join " . tablename("zh_gjw_orders") . " b on a.id=b.cus_id " .$where." group by a.cusname ORDER BY a.time desc",$data);
}*/

$select_sql =$sql." LIMIT " .($pageindex - 1) * $pagesize.",".$pagesize;
$registers=pdo_fetchall($select_sql,$data);
for ($i=0; $i <count($registers) ; $i++) { 
    $user=pdo_get('zh_gjw_register',array('uniacid'=>$_W['uniacid'],'openid' =>$registers[$i]['openid']));
 	$linshi=pdo_get('zh_gjw_orders', array('cus_id' => $registers[$i]['id'], 'uniacid' => $_W['uniacid'],'state'=>4), array('sum(ofees) as total_money'));
	$balance=pdo_get('zh_gjw_balance', array('c_id' => $registers[$i]['id'], 'uniacid' => $_W['uniacid'],'sysbzj'=>1), array('sum(fee) as total_money'));
    $cash=pdo_get('zh_gjw_cashlist', array('u_id' => $user['id'], 'uniacid' => $_W['uniacid']), array('sum(cash) as total_money'));
    $cashs=pdo_get('zh_gjw_cashlist', array('u_id' => $user['id'], 'uniacid' => $_W['uniacid'],'state'=>3), array('sum(cash) as total_money'));
	$registers[$i]['ofees']=round($linshi['total_money']+$balance['total_money'],2);
	$registers[$i]['yofees']=round($linshi['total_money']+$balance['total_money']-$cash['total_money']+$cashs['total_money'],2);
}
$pager = pagination($total, $pageindex, $pagesize);
if($op=='delete'){
 	 $file=pdo_get('zh_gjw_cusmanage',array('id'=>$_GPC['id']));
    $imgs=explode(",",$file['cardimg']);
    $url=str_replace('https://','',$_W['attachurl_local']);
    unlink('/www/wwwroot/'.$url.$file['liceneimg']);
    unlink('/www/wwwroot/'.$url.$file['bannerimg']);
    for ($i=0; $i <count($imgs) ; $i++) { 
      unlink('/www/wwwroot/'.$url.$imgs[$i]);
    }
    $duser=pdo_get('zh_gjw_cusmanage',array('id'=>$_GPC['id'])); 
    $uid=pdo_get('users',array('username'=>$duser['phone']));
    pdo_delete('users',array('username'=>$duser['phone']));
    pdo_delete('uni_account_users',array('uid'=>$uid['uid']));
    pdo_delete('users_permission',array('uid'=>$uid['uid']));
    $res=pdo_delete('zh_gjw_cusmanage',array('id'=>$_GPC['id']));
    if($res){
      message('删除成功',$this->createWebUrl('cusmanage',array()),'success');
    }else{
      message('删除失败','','error');
    }
}

if($_GPC['op']=='pcusm'){
	$res=pdo_update('zh_gjw_cusmanage',array('type'=>0),array('id'=>$_GPC['id']));
	if($res){
     message('', 'referer', 'success');
    }else{
          message('失败！','','error');
    }
}
if($_GPC['op']=='dcusm'){
	$res=pdo_update('zh_gjw_cusmanage',array('type'=>1),array('id'=>$_GPC['id']));
	if($res){
     message('', 'referer', 'success');
    }else{
          message('失败！','','error');
    }
}
if($_GPC['op']=='tg'){
  include_once IA_ROOT . '/addons/zh_gjw/cert/WxPay.Api.php';
  load()->model('account');
  load()->func('communication');
  $WxPayApi = new WxPayApi();
  $input = new WxPayRefund();
  $path_cert = IA_ROOT . "/addons/zh_gjw/cert/".'apiclient_cert_' . $_W['uniacid'] . '.pem';
  $path_key = IA_ROOT . "/addons/zh_gjw/cert/".'apiclient_key_' . $_W['uniacid'] . '.pem';
        function set_msg($_W,$_GPC){
            $ress=pdo_get('zh_gjw_system',array('uniacid'=>$_W['uniacid']));
            $user=pdo_get('zh_gjw_cusmanage',array('id'=>$_GPC['id']));
            $formwork ='{
                "touser": "'.$user["openid"].'",
                "template_id": "'.$ress["templeid"].'",
                "form_id":"'.$user['formid'].'",
                "data": {
                    "keyword1": {
                        "value": "'.$user['cusname'].'",
                        "color": "#173177"
                    },
                    "keyword2": {
                        "value":"商家认证审核通过",
                        "color": "#173177"
                    }
                }  
            }';
            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$ress['accessToken']."";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
            curl_setopt($ch, CURLOPT_POST,1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,$formwork);
            $data = curl_exec($ch);
            curl_close($ch);
           return $data;
        }
        //echo set_msg($_W,$_GPC);
  $refund_order =pdo_get('zh_gjw_cusmanage',array('id'=>$_GPC['id'])); 
        $tuser['username']=$refund_order['phone'];
        $tuser['password']=$refund_order['password'];
        $tuser['salt']; 
        $uid = user_register($tuser,null);
        if ($uid > 0) {
            unset($tuser['password']);
            $data = array(
                'uniacid' => $_W['uniacid'],
                'uid' => $uid,
                'role' => 'operator',
            );
            $exists = pdo_fetch("SELECT * FROM " . tablename('uni_account_users') . " WHERE uid = :uid AND uniacid = :uniacid", array(':uniacid' => $_W['uniacid'], ':uid' => $uid));
            if (empty($exists)) {
                pdo_insert('uni_account_users', $data);
            }
            //permission
            pdo_insert('users_permission', array(
                'uid' => $uid,
                'uniacid' => $_W['uniacid'],
                'url' => '',
                'type' => 'zh_gjw',
            ));
        }
        $res=pdo_update('zh_gjw_cusmanage',array('sh'=>2),array('id'=>$_GPC['id']));
        if($res){
          message('', 'referer', 'success');
        }else{
              message('失败！','','error');
        }
}
if($_GPC['op']=='jj'){
  include_once IA_ROOT . '/addons/zh_gjw/cert/WxPay.Api.php';
  load()->model('account');
  load()->func('communication');
  $WxPayApi = new WxPayApi();
  $input = new WxPayRefund();
  $path_cert = IA_ROOT . "/addons/zh_gjw/cert/".'apiclient_cert_' . $_W['uniacid'] . '.pem';
  $path_key = IA_ROOT . "/addons/zh_gjw/cert/".'apiclient_key_' . $_W['uniacid'] . '.pem';
  $refund_order =pdo_get('zh_gjw_cusmanage',array('id'=>$_GPC['id'])); 
        function set_msg($_W,$_GPC){
            $ress=pdo_get('zh_gjw_system',array('uniacid'=>$_W['uniacid']));
            $user=pdo_get('zh_gjw_cusmanage',array('id'=>$_GPC['id']));
            $formwork ='{
                "touser": "'.$user["openid"].'",
                "template_id": "'.$ress["templeid"].'",
                "form_id":"'.$user['formid'].'",
                "data": {
                    "keyword1": {
                        "value": "'.$user['cusname'].'",
                        "color": "#173177"
                    },
                    "keyword2": {
                        "value":"商家认证审核未通过",
                        "color": "#173177"
                    }
                }  
            }';
            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$ress['accessToken']."";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
            curl_setopt($ch, CURLOPT_POST,1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,$formwork);
            $data = curl_exec($ch);
            curl_close($ch);
           return $data;
        }
        echo set_msg($_W,$_GPC);
        $res=pdo_update('zh_gjw_cusmanage',array('sh'=>3,'pay'=>2),array('id'=>$_GPC['id']));
        if($res){
          message('', 'referer', 'success');
        }else{
              message('失败！','','error');
        }
} 

include $this->template('web/cusmanage');